package 刷题10月.链表;
import java.util.*;

// https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e?tpId=117&&tqId=37746&rp=1&ru=/activity/oj&qru=/ta/job-code-high/question-ranking
public class NC50链表中的节点每k个一组翻转1002 {

//https://blog.csdn.net/weixin_43207025/article/details/112795592
//
//https://blog.csdn.net/weixin_43852700/article/details/117756355
      public class ListNode {
        int val;
        ListNode next = null;
        public ListNode(int val){
            this.val=val;
          }
      }



    /*
     * public class ListNode {
     *   int val;
     *   ListNode next = null;
     * }
     */

    public class Solution {
        /**
         *
         * @param head ListNode类
         * @param k int整型
         * @return ListNode类
         */
        public ListNode reverseKGroup (ListNode head, int k) {
            // write code here
            if (head == null || head.next == null || k < 2) return head;
            ListNode res = new ListNode(-1);
            res.next = head;
            ListNode pre = res, cur = head, tmp;
            int len = 0;
            while (head != null) {
                len++;
                head = head.next;
            }

            for (int i = 0; i < len / k; i++) {
                for (int j = 1; j < k; j++) {    // 因为cur = head, 已经算一个
                    tmp = cur.next;
                    cur.next = tmp.next;
                    tmp.next = pre.next;
                    pre.next = tmp;
                }
                pre = cur;
                cur = pre.next;
            }
            return res.next;
        }
    }


}
